from copy import deepcopy
import pandas as pd
from jili.core.printlog import print
from jili.data.db import getdb_client
from research.pos import pos_frame
import datetime

from jili.data.db import tradecal

class pos(pos_frame):
    def __init__(self, cash=100000000, fee=0.0008, posrate_limit=1, targetnum=60, trademode="close", ip="127.0.0.1",tardedelay=0, priceurl=r"G:\price",isdetail=False):
        super(pos,self).__init__(priceurl,cash,isdetail)
        self.fee = fee
        self.targetnum = targetnum
        self.trademode = trademode
        self.tardedelay=tardedelay
        self.buysignals = {}
        self.sellsignals = {}
        self.posnum = 0
        self.tradeNo=0
        self.prebars = {}
        self.posrate_limit=posrate_limit
        self.ip = ip
        self.cashflow = [{"precash": cash, "balance": cash}]
        self.signal_count={"buy":0,"sell":0}
        self.trade_count = {"buy": 0, "sell": 0}



    def calc_avlfund(self):
        return self.fund["cash"]-self.holdcash

    def get_benck_net_add_time(self, index_obj):
        t = list(self.fund_his.keys())
        t.sort()
        rst = self.getbenckmark(index_obj, t)
        posrate_his = pd.Series(self.posrate_his)
        kd = pd.DataFrame(rst)
        kd["net"] = kd["CLOSE"].pct_change()
        kd["net"] = kd["net"] + 1
        kd['timekey'] = pd.to_datetime(kd['timekey'])
        kd.set_index('timekey', inplace=True)
        temp = kd["net"][posrate_his[posrate_his > 0].index]
        temp = temp.cumprod()
        temp = temp.reindex(t).fillna(method='ffill')
        temp = temp.fillna(1)
        temp = temp.to_list()
        return temp

    def resetposrate(self, posrate_limit, date, tradebars,isupdate_posrate_limit=True):
        if posrate_limit > 1:
            print("不支持超过1倍的杠杠")
            return False
        if posrate_limit < self.posrate_limit:
            print("减仓", posrate_limit, date, self.posrate_limit)
            for obj, p in self.pos.items():
                for bs ,v in p.items():
                    if v["qty"] > 0:
                        if obj not in tradebars.keys():
                            print("退市票，ondayend卖出", date, obj, self.prebars[obj]["close"])
                            self.sell(timekey=date, obj=obj, price=self.prebars[obj]["close"],posrate=1, msg="检查到退市")
                        else:
                            t = tradebars[obj]
                            price = t[self.trademode]
                            if obj not in tradebars.keys():
                                print("setposrate err not exits", obj)
                            else:
                                sellrate = (self.posrate_limit - posrate_limit) / self.posrate_limit
                                self.sell(timekey=date, obj=obj, price=price, posrate=sellrate, msg="减仓" + str(self.posrate_limit) + "->" + str(posrate_limit))
        elif posrate_limit > self.posrate_limit:
            print("加仓", posrate_limit, date, self.posrate_limit)
            balance=self.fund["balance"]
            pre_stock_values=balance/self.targetnum
            for obj, p in self.pos.items():
                for bs, v in p.items():
                    if v["qty"] > 0:
                        if obj not in tradebars.keys():
                            print("退市票，ondayend卖出", date, obj, self.prebars[obj]["close"])
                            self.sell(timekey=date, obj=obj, price=self.prebars[obj]["close"],posrate=1, msg="检查到退市")
                        else:
                            t = tradebars[obj]
                            price = t[self.trademode]
                            if obj not in tradebars.keys():
                                print("setposrate err not exits", obj)
                            else:
                                amount = pre_stock_values*posrate_limit-v["value"]
                                self.buy(timekey=date, obj=obj, price=price, amount=amount, msg="加仓" + str(self.posrate_limit) + "->" + str(posrate_limit))
        elif posrate_limit == 0:
            print("清仓", posrate_limit, date, self.posrate_limit)
            for obj, p in self.pos.items():
                for bs, v in p.items():
                    if v["qty"] > 0:
                        if obj not in tradebars.keys():
                            print("退市票，ondayend卖出", date, obj, self.prebars[obj]["close"])
                            self.sell(timekey=date, obj=obj, price=self.prebars[obj]["close"],posrate=1, msg="检查到退市")
                        else:
                            t = tradebars[obj]
                            price = t[self.trademode]
                            if obj not in tradebars.keys():
                                print("setposrate err not exits", obj)
                            else:
                                sellrate = 1
                                self.sell(timekey=date, obj=obj, price=price, posrate=sellrate, msg="清仓" + str(self.posrate_limit) + "->" + str(posrate_limit))
        if isupdate_posrate_limit:
            self.posrate_limit = posrate_limit
    def signal_buy(self,obj,timekey,signal,p):
        self.signal_count["buy"]=self.signal_count["buy"]+1
        if self.tardedelay==0:
            qty=signal.get("qty",None)
            amount=signal.get("amount",None)
            posrate = signal.get("posrate", None)
            is_commission=signal.get("is_commission",False)
            if "buyprice" in signal.keys():
                price=signal["buyprice"]
            elif "price" in signal.keys():
                price=signal["price"]
            else:
                price=p[self.trademode]
            # price = signal.get("buyprice", signal.get("price", p[self.trademode]))
            msg=signal.get("buyinfo",signal.get("info",""))
            if qty is None and amount is None and posrate is None:
                posrate=1
            r0,r1= self.buy(timekey,obj,price,qty=qty,amount=amount,posrate=posrate,msg=msg,is_commission=is_commission)
            if not r0:
                signal["buyinfo"]=msg+"-pos:"+r1
        else:
            if obj not in self.buysignals.keys():
                self.buysignals[obj]={}
            runtk=tradecal.gettradeday(timekey,self.tradedelay)
            if runtk not in self.buysignals[obj].keys():
                self.buysignals[obj][runtk]=[]
            self.buysignals[obj][runtk].append(signal)
    def signal_sell(self,obj,timekey,signal,p):
        self.signal_count["sell"] = self.signal_count["sell"] + 1
        if self.tardedelay==0:
            qty = signal.get("qty", None)
            amount = signal.get("amount", None)
            posrate = signal.get("posrate", None)
            is_commission = signal.get("is_commission", False)
            if "sellprice" in signal.keys():
                price = signal["sellprice"]
            elif "price" in signal.keys():
                price = signal["price"]
            else:
                price = p[self.trademode]
            msg = signal.get("buyinfo", signal.get("info", ""))
            if qty  is None and amount  is None and posrate   is None:
                posrate = 1
            self.sell(timekey,obj,price,qty=qty,amount=amount,posrate=posrate,msg=msg,is_commission=is_commission)
        else:
            if obj not in self.sellsignals.keys():
                self.sellsignals[obj]={}
            runtk=tradecal.gettradeday(timekey,self.tradedelay)
            if runtk not in self.sellsignals[obj].keys():
                self.sellsignals[obj][runtk]=[]
            self.sellsignals[obj][runtk].append(signal)
    def buy(self, timekey, obj, price,qty=None,posrate=1,amount=None,msg="",is_commission=False):
        """

        Args:
            timekey:
            obj:
            price:
            qty:
            posrate:
            amount:
            msg:
            is_commission: 下单价格是否包含 费用；默认不包含，包含时使用策略自动评估费用等级场景

        Returns:

        """
        self.posnum = self.getposnum()
        if is_commission == False:
            fee=price*self.fee
            price = price * (1 + self.fee)
        else:
            fee=0
            price = price
        if (self.targetnum == self.posnum) and (obj not in self.pos.keys()):
            print(timekey, obj, price, "已经达到持有目标股票数", self.posnum)
            return False,""
        elif self.posrate_limit == 0:
            print(timekey, obj, price, "清仓线，不再开仓", self.posrate_limit)
            return False,""
        else:
            cash=self.calc_avlfund()
            if amount   is None:
                if posrate is None:
                    if qty is None:
                        print(timekey, obj, price, "请指定，amount or posrate or qty", cash)
                        return False, ""
                    else:
                        amont0=qty*price
                        if amont0>cash:
                            print(timekey, obj, price, "现金不足", cash,amont0)
                            return False, ""
                else:
                    if cash < 100:
                        print(timekey, obj, price, "现金不足", cash)
                        return False,""
                    else:
                        if self.targetnum > self.posnum:
                            amont0=cash/(self.targetnum-self.posnum+self.targetnum*(1-self.posrate_limit)/self.posrate_limit)
                        else:
                            amont0 = self.posrate_limit * cash / self.targetnum
                    amont0=amont0*posrate
            else:
                if cash < amount:
                    amont0 = cash
                else:
                    amont0 = amount
            if amont0 > 100:
                self.tradeNo = self.tradeNo + 1
                balance = {"precash": cash, "date": timekey, "tradeNo": self.tradeNo}
                order=self.create_order()
                order0={"obj":obj,"bs":"buy","buyprice":price,"buyamount":amont0,"qty":amont0/price,"opentimekey":timekey,"buymsg":msg,
                       "buy_precash":cash,"targetnum":self.targetnum,"posnum":self.posnum,"posrate":1}
                order.update(order0)
                order["fee"]=order["qty"]*fee
                if obj in self.pos.keys():
                    p = self.pos[obj]["buy"]
                    if p["qty"] == 0:
                        qty = amont0 / price
                        print("新增买入", timekey, obj, price, qty,posrate, amount,amont0,msg)
                        p["qty"] = amont0 / price
                        p["costprice"] = price
                        p["costamount"] = amont0
                        p["detail"] = [order]
                        p["highprice"] = price
                        p["fee"] = p["fee"] + fee * p["qty"]
                    else:
                        qty = amont0 / price
                        print("买入增仓", timekey, obj, price, qty,posrate, amount,amont0,msg)
                        amont1 = p["costamount"] + amont0
                        p["qty"] = p["qty"] + amont0 / price
                        p["costprice"] = amont1 / p["qty"]
                        p["costamount"] = amont1
                        p["detail"].append(order)
                        p["fee"] = p["fee"] + fee * p["qty"]
                    p["openvalue"] = p["openvalue"] + amont0
                else:
                    qty=amont0 / price
                    print("新增买入", timekey, obj, price,qty,posrate, amount,amont0,msg)
                    p=self.create_pos()
                    p0={"obj":obj,"bs":"buy","costprice":price,"highprice":price,"costamount":amont0,"qty":qty,"close_pl":0,"closevalue":0,"openvalue":amont0,"detail":[order]}
                    p.update(p0)
                    self.pos[obj]={}
                    self.pos[obj]["buy"] = p

                self.cash2pos(amont0)
                balance["amount"] = amont0
                balance["balance"] = cash
                balance.update({"targetnum": self.targetnum, "posnum": self.getposnum(), "posrate": self.posrate_limit})
                balance["msg"] = str(order)
                self.cashflow.append(balance)
                self.trade_count["buy"] = self.trade_count["buy"] + 1
                return True,str(self.tradeNo)
            else:
                print("验资失败，资金不足100元")
                return False,""
    def sell(self, timekey, obj, price,qty=None,posrate=1,amount=None,msg="",is_commission=False):
        pos = self.getposnum()
        if obj in self.pos.keys():
            p = self.pos[obj]["buy"]
            if p["qty"] > 0:
                if posrate is None:
                    if qty is None:
                        if amount:
                            posrate=amount/(p["qty"]*price)
                        else:
                            return False,"数量，仓位，金额必须指定一个"
                    else:
                        posrate=qty/p["qty"]
                if posrate > 0.99:
                    posrate = 1
                pl = 0
                value = 0
                if posrate == 1:
                    qty=p["qty"]
                    # print("新增买入", timekey, obj, price, qty, posrate, amount, amont0, msg)
                    print("全部卖出", timekey, obj, price, qty,posrate,amount,msg,p["qty"])
                    for i in p["detail"]:
                        self.tradeNo = self.tradeNo + 1
                        order0 = deepcopy(i)
                        order = {}
                        order["sellprice"] = price
                        order["closetimekey"] = timekey
                        order["buyamount"] = i["qty"] * i["buyprice"]
                        if is_commission == False:
                            fee= i["qty"] * price * self.fee
                            order["pl"] = i["qty"] * (price * (1 - self.fee) - i["buyprice"])
                            order["sellamount"] = i["qty"] * price * (1 - self.fee)
                            order["closeamount"] =order["sellamount"]
                        else:
                            fee=0
                            order["pl"] = i["qty"] * (price - i["buyprice"])
                            order["sellamount"] = i["qty"] * price
                            order["closeamount"] = order["sellamount"]
                        order["plr"] = order["pl"] / order["buyamount"]
                        order["fee"]=(order["buyamount"]/i["buyamount"])*i["fee"]+fee
                        order["sellmsg"] = msg
                        pl = pl + order["pl"]
                        value = value + order["sellamount"]
                        precash = self.calc_avlfund()
                        #self.check_calcpl(order["pl"], order["sellamount"])
                        cash=self.pos2cash(order["sellamount"])
                        order0.update(order)
                        self.orders_his.append(order0)
                        balance = {"precash": precash, "date": timekey, "tradeNo": self.tradeNo}
                        balance["amount"] = -order["sellamount"]
                        balance["balance"] = cash
                        balance.update(
                            {"targetnum": self.targetnum, "posnum": pos - 1, "posrate": self.posrate_limit})
                        balance["msg"] = str(order)
                        self.cashflow.append(balance)
                    p["qty"] = 0
                    p["detail"] = []
                    p["pl"] = 0
                    p["value"] = 0
                    p["highprice"] = 0
                else:
                    qty = posrate * p["qty"]
                    if abs(p["qty"]-qty)<=0.001:
                        qty=p["qty"]
                    print("部分卖出", timekey, obj, price,qty, posrate,amount,msg,p["qty"])
                    if len(p["detail"]) == 1:
                        self.tradeNo = self.tradeNo + 1
                        i = p["detail"][0]
                        order0 = deepcopy(i)
                        order = {}
                        order["qty"] = qty
                        order["sellprice"] = price
                        order["closetimekey"] = timekey
                        order["buyamount"] = qty * i["buyprice"]
                        if is_commission == False:
                            fee=qty * price * self.fee
                            order["pl"] = qty * (price * (1 - self.fee) - i["buyprice"])
                            order["sellamount"] = qty * price * (1 - self.fee)
                            order["closeamount"] = order["sellamount"]
                        else:
                            fee=0
                            order["pl"] = qty * (price - i["buyprice"])
                            order["sellamount"] = qty * price
                            order["closeamount"] = order["sellamount"]
                        order["plr"] = order["pl"] / order["buyamount"]
                        order["fee"] = (order["buyamount"]/order0["buyamount"])*order0["fee"] + fee
                        order["posrate"]=posrate
                        order["sellmsg"] = msg
                        pl = pl + order["pl"]
                        value = value + order["sellamount"]
                        i["qty"] = p["qty"] - qty
                        p["qty"] = i["qty"]
                        if is_commission == False:
                            p["pl"] = p["qty"] * (price * (1 - self.fee) - i["buyprice"])
                            p["value"] = p["qty"] * price * (1 - self.fee)
                        else:
                            p["pl"] = p["qty"] * (price - i["buyprice"])
                            p["value"] = p["qty"] * price
                        precash=self.calc_avlfund()
                        #self.check_calcpl(order["pl"], order["sellamount"])
                        cash=self.pos2cash(order["sellamount"])
                        order0.update(order)
                        self.orders_his.append(order0)
                        balance = {"precash": precash, "date": timekey, "tradeNo": self.tradeNo}
                        balance["amount"] = -order["sellamount"]
                        balance["balance"] = cash
                        balance.update(
                            {"targetnum": self.targetnum, "posnum": pos, "posrate": self.posrate_limit})
                        balance["msg"] = str(order)
                        #self.tradeamount_total = self.tradeamount_total + abs(balance["amount"])
                        self.cashflow.append(balance)
                    else:
                        while qty > 0:
                            i = p["detail"].pop(0)
                            if i["qty"] <= qty:
                                qty0 = i["qty"]
                            else:
                                qty0 = qty
                            self.tradeNo = self.tradeNo + 1
                            order0 = deepcopy(i)
                            order = {}
                            order["qty"] = qty0
                            order["sellprice"] = price
                            order["buyamount"] = qty0 * i["buyprice"]
                            order["closetimekey"] = timekey
                            if is_commission == False:
                                order["pl"] = qty0 * (price * (1 - self.fee) - i["buyprice"])
                                order["sellamount"] = qty0 * price * (1 - self.fee)
                                order["closeamount"] = order["sellamount"]
                            else:
                                order["pl"] = qty0 * (price - i["buyprice"])
                                order["sellamount"] = qty0 * price
                                order["closeamount"] = order["sellamount"]
                            order["plr"] = order["pl"] / order["buyamount"]
                            # order["fee"] = (order["buyamount"] / order0["buyamount"]) * order0["fee"] + fee
                            order["sellmsg"] = msg
                            pl = pl + order["pl"]
                            value = value + order["sellamount"]
                            precash = self.calc_avlfund()
                            #self.check_calcpl(order["pl"], order["sellamount"])
                            cash = self.pos2cash(order["sellamount"])
                            order0.update(order)
                            self.orders_his.append(order0)
                            balance = {"precash": precash, "date": timekey, "tradeNo": self.tradeNo}
                            balance["amount"] = -order["sellamount"]
                            balance["balance"] = cash
                            balance.update(
                                {"targetnum": self.targetnum, "posnum": pos, "posrate": self.posrate_limit})
                            balance["msg"] = str(order)
                            #self.tradeamount_total = self.tradeamount_total + abs(balance["amount"])
                            self.cashflow.append(balance)
                            qty = qty - i["qty"]
                            if qty < 0:
                                i["qty"] = i["qty"] - qty0
                                p["detail"].insert(0, i)
                        p["qty"] = p["qty"] * (1 - posrate)
                        if is_commission == False:
                            fee=p["qty"] * price *  self.fee
                            p["pl"] = p["qty"] * (price * (1 - self.fee) - i["buyprice"])
                            p["value"] = p["qty"] * price * (1 - self.fee)
                        else:
                            fee=0
                            p["pl"] = p["qty"] * (price - i["buyprice"])
                            p["value"] = p["qty"] * price
                p["close_pl"] = p["close_pl"] + pl
                p["costamount"] = p["costamount"] * (1 - posrate)
                p["closevalue"] = p["closevalue"] + value
                p["fee"] = p["fee"] + fee
                self.trade_count["sell"] = self.trade_count["sell"] + 1
                return True,str(self.tradeNo)
            else:
                print("持仓不存在", timekey, obj, price, posrate)
                return False,""
        else:
            print("持仓不存在", timekey, obj, price, posrate)
            return False, ""
    def draw_html_market_sentiment_report(self,url):
        import pyecharts.options as opts
        from pyecharts.charts import Line, Grid
        rst = pd.Series(self.fund_his) / self.cash0
        rst = pd.DataFrame(rst, columns=["fund"])
        rst["timekey"] = rst.index
        rst["x"] = rst["timekey"].apply(lambda i: i.strftime("%Y%m%d"))
        t = list(self.fund_his.keys())
        t.sort()
        y01 = self.get_benck_net("000300",t)
        y02 = self.get_benck_net("000905",t)
        y03 = self.get_benck_net("399006",t)
        c = (
            Line(init_opts=opts.InitOpts(height="842px", width="1842px"))
                .add_xaxis(rst["x"].to_list())
                .set_global_opts(title_opts=opts.TitleOpts(title="pos"),
                                 yaxis_opts=opts.AxisOpts(
                                     name="数据1",
                                     name_location="start",
                                     type_="value",
                                     is_inverse=False,
                                     axistick_opts=opts.AxisTickOpts(is_show=False),
                                     splitline_opts=opts.SplitLineOpts(is_show=True),
                                 ),
                                 tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
                                 datazoom_opts=[
                                     opts.DataZoomOpts(type_="inside", range_start=0, range_end=100),
                                 ],
                                 xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False,
                                                          splitline_opts=opts.SplitLineOpts(is_show=True)),
                                 )
                .extend_axis(
                yaxis=opts.AxisOpts(
                    name="数据2",
                    min_='dataMin',
                    max_='dataMax',
                    splitline_opts=opts.SplitLineOpts(is_show=True)))
                .add_yaxis("沪深300", y01, yaxis_index=0, linestyle_opts=opts.LineStyleOpts(width=1),
                           label_opts=opts.LabelOpts(is_show=False), )
                .add_yaxis("中证500", y02, yaxis_index=0, linestyle_opts=opts.LineStyleOpts(width=1),
                           label_opts=opts.LabelOpts(is_show=False), )
                .add_yaxis("创业板", y03, yaxis_index=0, linestyle_opts=opts.LineStyleOpts(width=1),
                           label_opts=opts.LabelOpts(is_show=False), )
        )
        date = str(datetime.datetime.today())[:10]
        date = date[:4] + date[5:7] + date[8:10]
        htmlfigurl = url + '日报' +date+ ".html"
        color = 0
        color_set = ['#483D8B','#8470FF','#FF8247','#458B00','#00BFFF',
                     '#4682B4','#B0C4DE','#00CED1','#FF3030','#8B1A1A',
                     '#98FB98','#32CD32','#6B8E23','#FFFF00','#DAA520',
                     '#B8860B']
        for i, index in self.otherdata_graph.items():
            if i in self.other.keys():
                y0 = list(self.other[i].values())
                c.add_yaxis(series_name=i,
                            y_axis=y0,
                            yaxis_index=index,
                            linestyle_opts=opts.LineStyleOpts(width=2.5),
                            areastyle_opts=opts.AreaStyleOpts(opacity=0.1),
                            label_opts=opts.LabelOpts(is_show=False),
                            color = color_set[color]
                            )
            else:
                print("pos.other 不存在数据", i)
            color = color + 1
        c.render(htmlfigurl)
    def calc_fund(self):
        value=0
        for obj,v in self.pos.items():
            for bs,p in v.items():
                if p["qty"] > 0:
                    if obj not in self.bar_pool.keys():
                        key=list(self.bar_pool.keys())[0]
                        date=self.bar_pool[key]["timekey"]
                        print("退市票，ondayend卖出", date, obj, self.prebars[obj]["close"])
                        self.sell(timekey=date, obj=obj, price=self.prebars[obj]["close"], msg="检查到退市")
                    else:
                        t = self.bar_pool[obj]
                        price = t["close"] * (1 - self.fee)
                        if "close_pl" not in p.keys():
                            p["close_pl"] = 0
                            p["closevalue"] = 0
                        p["value"] = price * p["qty"]
                        p["pl"] = p["value"] - p["costamount"]
                        value = value + p["value"]
                        if price > p["highprice"]:
                            p["highprice"] = price
        self.fund["margin"]=value
        self.fund["balance"]=self.fund["margin"]+self.fund["cash"]
        return self.fund
    def getfundpos(self,date, data):
        self.calc_fund()
        return self.fund,self.pos
    def ondayend(self, date, data={}):#默认第一天净值处理
        d = datetime.datetime(date.year, date.month, date.day)
        if d not in self.fund_his.keys():
            if not self.fund_his:
                t1 = tradecal.getpretradeday(datetime.datetime(date.year, date.month, date.day))
                self.fund_his[t1] = self.cash0
                self.posrate_his[t1] = 0
                self.return_his[t1]=0
            prebalance = self.fund["prebalance"]
            self.calc_fund()
            if self.isdetail:
                issavepos = False
                for obj, v in self.pos.items():
                    for bs, p in v.items():
                        if p["qty"] > 0:
                            issavepos = True
                if issavepos:
                    self.pos_his[date] = deepcopy(self.pos)
            cashin=self.fund["cashin"]
            fund0=self.fund["balance"]
            if self.maxfund < fund0:
                self.maxfund = fund0
            self.fund_his[date] = fund0
            self.curr_return = (fund0 - self.cash0- self.cashin_total) / (self.cash0+ self.cashin_total)
            self.return_byday = (fund0 - prebalance-cashin) / (prebalance + cashin)
            self.return_his[date] = self.return_byday
            self.curr_posrate = (fund0 - self.fund["cash"]) / fund0
            self.posrate_his[date] = self.curr_posrate
            self.fund["prebalance"]=fund0
            self.fund["cashin"]=0

            print("日终计算",d, date, self.curr_posrate, fund0, self.curr_return,self.return_byday)
        if data:
            self.prebars = data
    def clearpos(self, date, data={},msg="",trademode="close",posrate=1):
        isprint1 = True
        isprint2 = False
        if self.isclosetime:
            isprint1 = False
        self.isclosetime = True
        """:cvar
        mode:0  按价直接清仓；不处理
            1:按价排队清仓；看成交量；最后一分钟加价卖出
            3.按每次成交百分比vwap撮合成交
        """
        for obj, v in self.pos.items():
            for bs, p in v.items():
                if p["qty"] > 0:
                    isprint2=True
                    price = self.get_data_tradeprice(obj,data,trademode=trademode)
                    if price is None:
                        price = self.get_data_tradeprice(obj, self.predata,trademode=trademode)
                    if bs == "buy":
                        self.sell(timekey=date, obj=obj, price=price, posrate=posrate, msg=msg)
        if isprint1 and isprint2:
            print("清仓", date, msg)

pos_stock_avghold_byunit=pos